
package com.controller;


import java.util.Arrays;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.entity.TeacherEntity;
import com.entity.UserEntity;
import com.service.EmailService;
import com.service.TeacherService;
import com.service.impl.EmailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.annotation.IgnoreAuth;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.entity.AdminEntity;
import com.service.TokenService;
import com.service.AdminService;
import com.utils.MPUtil;
import com.utils.PageUtils;
import com.utils.R;

/**
 * 教师控制类
 */
@RequestMapping("teacher")
@RestController
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private EmailService emailService;

    /**
     * 登录
     */
    @IgnoreAuth
    @RequestMapping(value = "/login")
    public R login(String username, String password) {

        TeacherEntity teacher = teacherService.selectOne(new EntityWrapper<TeacherEntity>().eq("username", username));
        if(teacher==null){
            return R.error("用户不存在");
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        boolean matches = encoder.matches(password, teacher.getPassword());

        if(!matches) {
            return R.error("账号或密码不正确");
        }
        String token = tokenService.generateToken(teacher.getId(),username, "teachers", "教师");
        return R.ok().put("token", token);
    }

    /**
     * 注册
     */
    @IgnoreAuth
    @RequestMapping("/register")
    public R register(@RequestBody Map<String, Object> params) {
        String username = (String) params.get("username");
        String email = (String) params.get("email");
        String verificationCode = (String) params.get("verificationCode"); // 获取前端传递的验证码

        // 1. 检查用户名是否存在
        TeacherEntity t = teacherService.selectOne(new EntityWrapper<TeacherEntity>().eq("username", username));
        if (t != null) {
            return R.error("用户名已存在");
        }

        if (email == null || email.isEmpty()) {
            return R.error("邮箱不能为空");
        }
        t = teacherService.selectOne(new EntityWrapper<TeacherEntity>().eq("email", email));
        if(t!=null){
            return R.error("该邮箱已被注册");
        }
        if (verificationCode == null || verificationCode.isEmpty()) {
            return R.error("验证码不能为空");
        }

        if (!emailService.verifyCode(email, verificationCode)) {
            return R.error("验证码错误或已过期，请重新获取。");
        }

        TeacherEntity teacher = new TeacherEntity();
        teacher.setUsername(username);
        teacher.setName((String) params.get("name"));
        teacher.setEmail(email);
        teacher.setAvatar((String) params.get("avatar"));

        //加密密码
        String rawPassword = (String) params.get("password");
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encodedPassword = encoder.encode(rawPassword);
        teacher.setPassword(encodedPassword);


        teacherService.insert(teacher);

        ((EmailServiceImpl) emailService).clearVerificationCode(email);

        return R.ok("注册成功！");
    }

    /**
     * 退出
     */
    @GetMapping(value = "logout")
    public R logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return R.ok("退出成功");
    }

    /**
     * 密码重置
     */
    @IgnoreAuth
    @RequestMapping(value = "/resetPass")
    public R resetPass(String username, HttpServletRequest request){
        TeacherEntity teacher = teacherService.selectOne(new EntityWrapper<TeacherEntity>().eq("username", username));
        if(teacher==null) {
            return R.error("账号不存在");
        }
        teacher.setPassword("123456");
        teacherService.update(teacher,null);
        return R.ok("密码已重置为：123456");
    }

    /**
     * 列表
     */
    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params, TeacherEntity teacher){
        EntityWrapper<TeacherEntity> ew = new EntityWrapper<TeacherEntity>();
        PageUtils page = teacherService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.allLike(ew, teacher), params), params));
        return R.ok().put("data", page);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list( TeacherEntity teacher){
        EntityWrapper<TeacherEntity> ew = new EntityWrapper<TeacherEntity>();
        ew.allEq(MPUtil.allEQMapPre( teacher, "user"));
        return R.ok().put("data", teacherService.selectListView(ew));
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") String id){
        TeacherEntity teacher = teacherService.selectById(id);
        return R.ok().put("data", teacher);
    }

    /**
     * 获取用户的session用户信息
     */
    @RequestMapping("/session")
    public R getCurrUser(HttpServletRequest request){
        Long id = (Long)request.getSession().getAttribute("userId");
        TeacherEntity teacher = teacherService.selectById(id);
        return R.ok().put("data", teacher);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    public R save(@RequestBody TeacherEntity teacher){
//    	ValidatorUtils.validateEntity(user);
        if(teacherService.selectOne(new EntityWrapper<TeacherEntity>().eq("username", teacher.getUsername())) !=null) {
            return R.error("用户已存在");
        }
        teacherService.insert(teacher);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody TeacherEntity teacher){
//        ValidatorUtils.validateEntity(user);
        TeacherEntity t = teacherService.selectOne(new EntityWrapper<TeacherEntity>().eq("username", teacher.getUsername()));
        if(t!=null && t.getId()!=teacher.getId() && t.getUsername().equals(teacher.getUsername())) {
            return R.error("用户名已存在。");
        }
        teacherService.updateById(teacher);//全部更新
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
        teacherService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }

}
